/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * listSubCategoria.java
 *
 * Created on 27/11/2011, 16:26:51
 */
package visao;

import categoria.Categoria;
import fachada.FachadaBDR;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import subCategoria.SubCategoria;
import util.CamposObrigatoriosException;
import util.ErroAcessoRepositorioException;
import util.KeyValue;

/**
 *
 * @author Alberto
 */
public class listSubCategoria extends javax.swing.JFrame {

    public String[] titulos = new String[]{"#", "Descrição SubCategoria", "Categoria", "Status"};
    public DefaultTableModel defTable;
    public CadSubCategoria cadastroSubCategoria = new CadSubCategoria();

    /** Creates new form listSubCategoria */
    public listSubCategoria() {
        /** Creates new form listCategoria */
        try {
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();
            List<SubCategoria> listCategoria = objFachadaBDR.listarSubCategoriaAtivo();

            // Setando a tabela
            this.defTable = atualizaLista(listCategoria);

        } catch (CamposObrigatoriosException ex) {
            System.out.println(ex.getMessage());
        } catch (ErroAcessoRepositorioException ex) {
            System.out.println(ex.getMessage());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        initComponents();
        this.setLocationRelativeTo(null);
        this.setIconImage(new ImageIcon(getClass().getResource("/Imagens/visao.gif")).getImage());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        list_categoria = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        descricao_subcategoria = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        mensagem = new javax.swing.JLabel();

        setTitle("SubCategoria");
        setResizable(false);

        jTable1.setModel(this.defTable);
        jScrollPane1.setViewportView(jTable1);

        try {
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();

            List<Categoria> listCategoria = objFachadaBDR.listarCategoria("");

            list_categoria.addItem(new KeyValue("--- Favor Selecionar ---","0"));
            for (Categoria objCat : listCategoria) {
                list_categoria.addItem(new KeyValue(objCat.getNome(), Integer.toString(objCat.getIdCategoria())));
            }

        } catch (Exception e) {
        }

        jLabel1.setText("Categoria:");

        jLabel2.setText("Descrição SubCategoria");

        jButton1.setText("Buscar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Cadastrar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Editar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Atualizar");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText("Remover");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(list_categoria, javax.swing.GroupLayout.PREFERRED_SIZE, 277, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(descricao_subcategoria, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 101, Short.MAX_VALUE)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(279, 279, 279))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(mensagem, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 686, Short.MAX_VALUE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 686, Short.MAX_VALUE))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(36, 36, 36)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(list_categoria, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(descricao_subcategoria, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 330, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton3)
                    .addComponent(jButton4)
                    .addComponent(jButton5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(mensagem, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        try {
            if (!this.cadastroSubCategoria.isVisible()) {
                this.cadastroSubCategoria = new CadSubCategoria();
                this.cadastroSubCategoria.setVisible(true);
            }
            FachadaBDR objfaFachadaBDR = FachadaBDR.getInstancia();
            List<SubCategoria> listSubCategoria = objfaFachadaBDR.listarSubCategoriaAtivo();

            // Setando a tabela
            this.defTable = atualizaLista(listSubCategoria);

            // Setando a nova listagem
            jTable1.setModel(this.defTable);

            jTable1.revalidate();
            mensagem.setText("");
        } catch (Exception ex) {
            mensagem.setText(ex.getMessage());
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        try {
            // pegando a linha selecionada
            if (this.jTable1.getSelectedColumnCount() == 0) {
                throw new Exception("Favor selecionar uma Sub Categoria");
            }

            // Pegando a linha que está selecionada
            int linha = this.jTable1.getSelectedRow();
            // recuperando o Cpf do funcionario
            int idSubCategoria = (Integer) this.jTable1.getValueAt(linha, 0);

            FachadaBDR objfaFachadaBDR = FachadaBDR.getInstancia();

            SubCategoria objSubCategoria = objfaFachadaBDR.procurarSubCategoria(idSubCategoria);

            // se a tela de cargo ja estiver instanciada
            if (!this.cadastroSubCategoria.isVisible()) {
                this.cadastroSubCategoria = new CadSubCategoria(objSubCategoria.getIdSubCategoria());
                this.cadastroSubCategoria.setVisible(true);
            }
            // Listando os cargos
            List<SubCategoria> listSubCategoria = objfaFachadaBDR.listarSubCategoriaAtivo();

            // Setando a tabela
            this.defTable = atualizaLista(listSubCategoria);

            // Setando a nova listagem
            jTable1.setModel(this.defTable);

            // atualizando os cargos
            jTable1.revalidate();

            mensagem.setText("");
        } catch (Exception ex) {
            mensagem.setText(ex.getMessage());
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        try {
            FachadaBDR objfaFachadaBDR = FachadaBDR.getInstancia();

            // Listando os cargos
            List<SubCategoria> listSubCategoria = objfaFachadaBDR.listarSubCategoriaAtivo();

            // Setando a tabela
            this.defTable = atualizaLista(listSubCategoria);

            // Setando a nova listagem
            jTable1.setModel(this.defTable);

            // atualizando os cargos
            jTable1.revalidate();

            mensagem.setText("");
        } catch (Exception ex) {
            mensagem.setText(ex.getMessage());
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        try {
            // pegando a linha selecionada
            if (this.jTable1.getSelectedColumnCount() == 0 || this.jTable1.getSelectedColumnCount() > 1) {
                throw new Exception("Favor selecionar uma Sub Categoria");
            }

            int cancelar = JOptionPane.showConfirmDialog(null, "Deseja Remover esta Sub Categoria?");
            if (cancelar == JOptionPane.YES_OPTION) {
                try {
                    int linha = this.jTable1.getSelectedRow();

                    // recuperando o Cpf do funcionario
                    int idSubCategoria = (Integer) this.jTable1.getValueAt(linha, 0);

                    // instanciando a fachada
                    FachadaBDR objfaFachadaBDR = FachadaBDR.getInstancia();

                    // Listando os cargos
                    objfaFachadaBDR.removerSubCategoria(idSubCategoria);

                    // Listando os cargos
                    List<SubCategoria> listSubCategoria = objfaFachadaBDR.listarSubCategoriaAtivo();

                    // Setando a tabela
                    this.defTable = atualizaLista(listSubCategoria);

                    // Setando a nova listagem
                    jTable1.setModel(this.defTable);

                    jTable1.revalidate();

                    mensagem.setText("Removido com sucesso!");

                } catch (Exception ex) {
                    mensagem.setText(ex.getMessage());
                }
            }
        } catch (Exception e) {
            mensagem.setText(e.getMessage());
        }
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            // instanciando a fachada
            FachadaBDR objfaFachadaBDR = FachadaBDR.getInstancia();

            // Recuperendo os valores
            String descricaoSubcategoria = descricao_subcategoria.getText();
            int idCategoria = Integer.parseInt(((KeyValue) list_categoria.getSelectedItem()).getValue());

            // Listando as descrição produtos
            List<SubCategoria> listDescricaoProduto = objfaFachadaBDR.procurarSubCategoriaPorDescricaoPorCategoria(descricaoSubcategoria, idCategoria);

            // Setando a tabela
            this.defTable = atualizaLista(listDescricaoProduto);

            // Setando a nova listagem
            jTable1.setModel(this.defTable);
            jTable1.revalidate();

            if (listDescricaoProduto.size() > 0) {
                mensagem.setText("");
            } else {
                mensagem.setText("Nenhuma Sub Categoria encontrada!");
            }
        } catch (Exception ex) {
            mensagem.setText(ex.getMessage());
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(listSubCategoria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(listSubCategoria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(listSubCategoria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(listSubCategoria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new listSubCategoria().setVisible(true);
            }
        });
    }

    public DefaultTableModel atualizaLista(List<SubCategoria> listSubCategoria) {
        // Criando o objeto 
        Object[][] resposta = new Object[listSubCategoria.size()][4];

        for (int i = 0; i < resposta.length; i++) {
            SubCategoria objSubCategoria = listSubCategoria.get(i);
            resposta[i][0] = objSubCategoria.getIdSubCategoria();
            resposta[i][1] = objSubCategoria.getNome();
            resposta[i][2] = objSubCategoria.getCategoria().getNome();
            resposta[i][3] = (objSubCategoria.getStatusSubCategoria()) ? "Ativo" : "Inativo";
        }

        // Setando a tabela
        return new DefaultTableModel(resposta, titulos);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField descricao_subcategoria;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JComboBox list_categoria;
    private javax.swing.JLabel mensagem;
    // End of variables declaration//GEN-END:variables
}
